package org.bjf.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bjf.cache.CacheNameConfig;
import org.bjf.modules.core.service.BaseService;
import org.bjf.modules.sys.bean.SysUserRole;
import org.bjf.modules.sys.mapper.SysUserRoleMapper;
import org.bjf.modules.sys.query.SysUserRoleQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author bjf
 * @date 2017/11/27
 */
@Service
@Slf4j
public class SysUserRoleService extends
        BaseService<SysUserRoleMapper, SysUserRole, SysUserRoleQuery> {

    @Autowired
    private SysUserService sysUserService;
    @Override
    protected LambdaQueryWrapper<SysUserRole> buildQuery(SysUserRoleQuery q) {
        if (q == null) {
            return null;
        }
        LambdaQueryWrapper<SysUserRole> qw = new LambdaQueryWrapper<>();
        qw.eq(q.getSysUserId() != null, SysUserRole::getSysUserId, q.getSysUserId());
        qw.eq(q.getSysRoleId() != null, SysUserRole::getSysRoleId, q.getSysRoleId());
        return qw;
    }
    /**
     * 给用户分配角色
     */
    @CacheEvict(value = CacheNameConfig.RedisCacheEnum.Names.SYS, key = "'live:role:listByUser:' + #sysUserId")
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(long sysUserId, String roleIds) {
        String[] split = StringUtils.split(roleIds, ",");
        List<SysUserRole> list = new ArrayList<>(split.length);
        for (String roleId : split) {
            SysUserRole userRole = new SysUserRole().setSysUserId(sysUserId).setSysRoleId(Long.valueOf(roleId));
            list.add(userRole);
        }

        //===1、先删除用户原有角色
        this.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getSysUserId, sysUserId));

        //===2、批量新增用户角色
        this.addBatch(list);

        sysUserService.clearUserCache();

    }
}
